import './polyfill';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { NgModuleRef, Injector } from '@angular/core';
import { AppModule } from './app.module';
import { createCustomElement } from '@angular/elements';
import { MyWebComponent } from './my-webcomponent.component';

// 确保在浏览器环境中执行
if (typeof window !== 'undefined' && typeof document !== 'undefined') {
  // 直接在全局作用域中定义Web Component注册函数
  // 这样可以从外部直接调用进行调试
  window['registerMyWebComponent'] = async function() {
    try {
      console.log('Starting Angular Web Component registration process');
      
      // 获取Angular平台注入器
      const platform = platformBrowserDynamic();
      
      // 编译并获取模块引用
      const moduleRef: NgModuleRef<AppModule> = await platform.bootstrapModule(AppModule);
      
      console.log('Angular AppModule successfully bootstrapped');
      
      // 使用模块的注入器创建自定义元素
      const webComponent = createCustomElement(MyWebComponent, {
        injector: moduleRef.injector
      });
      
      console.log('Custom element factory created');
      
      // 注册Web Component
      if (!customElements.get('my-webcomponent')) {
        customElements.define('my-webcomponent', webComponent);
        console.log('my-webcomponent successfully registered as custom element');
        
        // 通知外部注册成功
        if (window['onWebComponentRegistered']) {
          window['onWebComponentRegistered']();
        }
      } else {
        console.log('my-webcomponent already registered');
      }
    } catch (err) {
      console.error('Error during web component registration:', err);
      
      // 通知外部注册失败
      if (window['onWebComponentRegistrationFailed']) {
        window['onWebComponentRegistrationFailed'](err);
      }
    }
  };
  
  // 启动Web Component注册过程
  console.log('Scheduling Web Component registration');
  // 使用setTimeout确保DOM已经准备好
  setTimeout(() => {
    window['registerMyWebComponent']();
  }, 100);
}

// 导出Web Component供其他应用使用
export * from './app.module';
export * from './my-webcomponent.component';